/*
 * @Author: lll 1280388921@qq.com
 * @Date: 2025-04-15 23:03:27
 * @LastEditors: lll 1280388921@qq.com
 * @LastEditTime: 2025-04-16 16:10:06
 * @FilePath: /lesson29/1.sharemem/comm.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once

#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include<string>
#include<cstring>
#include<cstdlib>
#include<sys/stat.h>
#include"log.hpp"

Log log;
using namespace std;


//共享内存的大小一般建议是4096的整数倍
//设置为4097 实际上操作系统分配了4096*2的大小给共享内存
//虽然操作系统分配了4096*2 但是你设置了4097也只能用4097
const int size=4096;

//冲突了改值就行
const string pathname="/home/lll";
int proj_id=0x1234;

#define FIFO_FILE "./myfifo"
#define MODE 0664

enum
{
    FIFO_CREATE_ERR=1,
    FIFO_OPEN_ERR,
    FIFO_DELETE_ERR
};

class Init
{
public:
    Init()
    {
         //创建管道
        int n=mkfifo(FIFO_FILE,MODE);
        if(n==-1)
        {
            perror("mkfifo");
            exit(FIFO_CREATE_ERR);
        }
    }
    ~Init()
    {
        //删除管道
        int m=unlink(FIFO_FILE);
        if(m==-1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERR);
        }
    }
};

key_t Getkey()
{
    key_t k=ftok(pathname.c_str(),proj_id);
    if(k<0)
    {
        log(Fatal,"ftok error : %s",strerror(errno));
        exit(1);
    }
    log(Info,"ftok sucess,key is 0x%x",k);
    return k;
}

int GetshmMenHelper(int flag)
{
    int k=Getkey();
    int shmid=shmget(k,size,flag);
    if(shmid<0)
    {
        log(Fatal,"create share memory error: %s",strerror(errno));
        exit(2);
    }
    log(Info,"create share memory success , shmid : %d",shmid);

    return shmid;
}

int Createshm()
{
    return GetshmMenHelper(IPC_CREAT|IPC_EXCL|0666);
}

int Getshm()
{
    return GetshmMenHelper(IPC_CREAT);
}